<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddContract.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogAddContract.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 5vh"
    @close="closeDialog"
  >
    <el-form
      ref="addOrEditFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="170"
      size=""
      style="padding-right: 10px; overflow: auto"
    >
      <el-row justify="start" style="margin-top: 10px">
        <el-col :span="itemSpan">
          <el-form-item label="所属企业" prop="corpName">
            <el-input v-model="formData.corpName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="姓名" prop="personName">
            <el-input v-model="formData.personName" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="itemSpan">
          <el-form-item label="合同编号" prop="code">
            <el-input v-model="formData.code" placeholder="请输入合同编号" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="合同类型" prop="type">
            <el-select v-model="formData.type" placeholder="请选择" clearable>
              <el-option v-for="item in contractTypes" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="合同签订日期" prop="signingDate">
            <el-date-picker
              v-model="formData.signingDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="合同起始日期" prop="startDate">
            <el-date-picker
              v-model="formData.startDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="合同终止日期" prop="endDate">
            <el-date-picker
              v-model="formData.endDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>

        <el-col :span="itemSpan">
          <el-form-item label="工资计算方式" prop="salaryCalculationMethod">
            <el-select v-model="formData.salaryCalculationMethod" placeholder="请选择" clearable>
              <el-option
                v-for="item in salaryCalculationMethods"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="工资标准" prop="wageStandard">
            <el-input v-model="formData.wageStandard" type="number" placeholder="请输入工资标准" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="工资支付日期" prop="salaryPaymentDate">
            <el-input v-model="formData.salaryPaymentDate" type="number" max="31" placeholder="请输入支付日期" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="上传合同附件" prop="attachments">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  <span>下载模板</span>仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddContract.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { CreatePersonContract } from "@/api/contract/index";
import { PersonContractForm } from "@/api/contract/types";
import { getDicts } from "@/store/modules/dict";
import { useScreen } from "@/store/modules/screen";
import { FormRules } from "element-plus/es/components/form/src/types";
import type { UploadUserFile } from "element-plus";
import moment from "moment";

//声明变量
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);
//合同类型
const contractTypes = getDicts("contractType");
//工资计算方式
const salaryCalculationMethods = getDicts("salaryCalculationMethod");

//上传文件列表
const fileList = ref<UploadUserFile[]>([]);
const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(900);
const itemSpan = ref(12);
const props = defineProps({
  dialogAddContract: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
    }),
  },
  workerInfo: {
    type: Object,
    default: () => ({
      personName: "",
      corpName: "",
      corpId: 0,
      personId: 0,
    }),
  },
});

const { dialogAddContract, workerInfo } = toRefs(props);

const emit = defineEmits(["sendClose"]);
const loading = ref(false);

const formData = reactive<PersonContractForm>({
  attachments: [],
});
const addOrEditFormRef = ref(ElForm);

//表单验证规则
const validatorAttachment = function (rule: any, value: any, callback: any) {
  if (fileList.value.length == 0) {
    callback(new Error("请上传附件!"));
    return;
  } else {
    callback();
  }
};
const rules = reactive<FormRules<PersonContractForm>>({
  type: [{ required: true, message: "请选择合同类型", trigger: "blur" }],
  signingDate: [{ required: true, message: "合同签订日期不能为空", trigger: "blur" }],
  startDate: [{ required: true, message: "合同起始日期不能为空", trigger: "blur" }],
  endDate: [
    { required: true, message: "合同终止日期不能为空", trigger: "blur" },
    {
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (moment(value).isBefore(formData.startDate)) {
          formData.endDate = undefined;
          return callback(new Error("合同终止日期不能早于合同签订日期"));
        }
        callback();
      },
    },
  ],
  salaryCalculationMethod: [{ required: true, message: "工资计算方式不能为空", trigger: "blur" }],
  wageStandard: [{ required: true, message: "工资标准不能为空", trigger: "blur" }],
  salaryPaymentDate: [
    { required: true, message: "工资发放日期不能为空", trigger: "blur" },
    {
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (parseInt(value) > 31) {
          formData.salaryPaymentDate = undefined;
          return callback(new Error("工资发放日期不能大于31天"));
        }
        if (parseInt(value) == 0) {
          formData.salaryPaymentDate = undefined;
          return callback(new Error("工资发放日期不能为0天"));
        }
        callback();
      },
    },
  ],
  code: [{ required: true, message: "合同编号不能为空", trigger: "blur" }],
  attachments: [
    {
      required: true,
      message: "请上传项目文件",
      trigger: "blur",
      validator: validatorAttachment,
    },
  ],
});

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 900;
    itemSpan.value = 12;
  }
}

const initForm = async function () {
  formData.corpName = workerInfo.value.corpName;
  formData.corpId = workerInfo.value.corpId;
  formData.personName = workerInfo.value.personName;
  formData.personId = workerInfo.value.personId;
};

onMounted(async () => {
  initScreen();
  fileList.value = [];
  initForm();
});

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
  formData.projectId = undefined;
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (fileList.value.length > 0) {
        formData.attachments = new Array<any>();
        fileList.value.forEach((item: any) => {
          if (item.status === "success") {
            if (item.response) {
              formData.attachments.push({ attachmentId: item.response.data });
            } else {
              formData.attachments.push({ attachmentId: item.uid });
            }
          }
        });
      }
      formData.signingType = 1;
      CreatePersonContract(formData)
        .then((resp) => {
          if (resp.type === 0) {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog(true);
            } else {
              ElMessage.warning(resp.msg);
            }
          } else {
            ElMessage.warning(resp.msg);
          }
        })
        .finally(() => (loading.value = false));
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
